package one.stand.event;

import com.jmp.base.ChatApi;
import com.jmp.base.dto.*;
import com.jmp.feign.*;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import one.stand.mapper.BusinessCardMapperExt;
import one.stand.model.BusinessCard;
import one.stand.model.Company;
import one.stand.model.ResultModel;
import one.stand.service.BusinessCardService;
import one.stand.service.CompanyBaseService;
import one.stand.service.sys.SysDictValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
@Async("asyncServiceExecutor")
@Slf4j
public class CardUpdateEventListener {
    @Autowired
    private TemplateFeign templateFeign;
    @Autowired
    private SunCodeFeign sunCodeFeign;
    @Autowired
    private SmsFeign smsFeign;
    @Autowired
    private ChatFeign chatFeign;
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private SysDictValueService sysDictValueService;

    @Autowired
    private BusinessCardService businessCardService;
    @Autowired
    private BusinessCardMapperExt businessCardMapperExt;

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void handle(CardUpdateEvent event) {
        log.info("card update");

        businessCardService.updatePerfectRate(event.getId());

        // 修改用户头像
        BusinessCard inModel = businessCardService.get(event.getId());
        userFeign.save(UserSaveDto.builder()
                .id(inModel.getUserId())
                .avatarUrl(inModel.getLogo())
                .build());
        chatFeign.save(ChatSaveDto.builder().userId(inModel.getUserId()).build());

        // 名片太阳码
        ResultModel<SunCodeCardResponse> resultModel = sunCodeFeign.card(SunCodeCardRequest.builder()
                .cardId(event.getId())
                .updateFlag(true)
                .build());
        if (resultModel.isSuccess()) {
            businessCardMapperExt.updateByPrimaryKeySelective(new BusinessCard() {{
                setCardId(event.getId());
                setWxTwoCode(resultModel.getData().getCodeUrl());
            }});
        }

        TemplateUpdateByCardRequest updateByCardRequest = TemplateUpdateByCardRequest.builder().cardId(event.getId()).build();
        templateFeign.updateByCard(updateByCardRequest);
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void handle(CardSaveEvent event) {
        log.info("card save");

        businessCardService.updatePerfectRate(event.getId());

        // 修改用户头像
        BusinessCard inModel = businessCardService.get(event.getId());
        userFeign.save(UserSaveDto.builder()
                .id(inModel.getUserId())
                .avatarUrl(inModel.getLogo())
                .build());
        chatFeign.save(ChatSaveDto.builder().userId(inModel.getUserId()).build());

        // 名片太阳码
        ResultModel<SunCodeCardResponse> resultModel = sunCodeFeign.card(SunCodeCardRequest.builder().cardId(event.getId()).build());
        if (resultModel.isSuccess()) {
            businessCardMapperExt.updateByPrimaryKeySelective(new BusinessCard() {{
                setCardId(event.getId());
                setWxTwoCode(resultModel.getData().getCodeUrl());
            }});
        }

//        if (event.isBoss() && event.isClientJxs()) {
//            // sms
//            DictDto sysDictValue = sysDictValueService.get2(SysDictValueService.Type.CONFIG, SysDictValueService.TypeName.SMS_JXS_SIGN);
//            if (Objects.nonNull(sysDictValue)) {
//                BusinessCard card = businessCardService.get(event.getId());
//                Company companyCreator = companyBaseService.getById(card.getCompanyId());
//                SmsParam smsParam = SmsParam.builder().company(companyCreator.getCompanyName()).build();
//                smsFeign.sendBatchSms(SmsSendRequest.builder()
//                        .type(SmsCodeEnums.jxsSign.getCode())
//                        .phones(Lists.newArrayList(sysDictValue.getValue()))
//                        .params(JSON.toJSONString(smsParam))
//                        .build());
//            } else {
//                log.warn("config:SMS_JXS_SIGN is null");
//            }
//        }

        //系统消息-员工申请
        if (!event.isBoss() && event.isNoPassword()) {
            BusinessCard card = businessCardService.get(event.getId());
            Company company = companyBaseService.getById(card.getCompanyId());
            chatFeign.msgSystem(ChatMsgSystemDto.builder()
                    .type(ChatApi.SYS_MSG_COMPANY_APPLY)
                    .toId(String.valueOf(company.getUserId()))
                    .textParams(new Object[]{card.getName()})
                    .build());
        }
    }

    @Data
    @Builder
    private static class SmsParam {
        private String company;
    }
}
